package com.easyaop.api.support.loadclass;

import com.easyaop.api.support.ClassDefiner;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class ClassDefinerAdapter extends AbstractClassDefiner {
    protected final ClassDefiner classDefiner;

    public ClassDefinerAdapter(MethodHandles.Lookup caller, Class<?> targetClass, ClassDefiner classDefiner) {
        super(caller, targetClass);
        this.classDefiner = classDefiner;
    }

    public ClassDefinerAdapter(int majorVersion, MethodHandles.Lookup caller, Class<?> targetClass,
                               ClassDefiner classDefiner) {
        super(majorVersion, caller, targetClass);
        this.classDefiner = classDefiner;
    }

    public static ClassDefiner newInstance(MethodHandles.Lookup caller, Class<?> targetClass) {
        int majorVersion = MajorVersion.getMajorVersion();
        ClassDefiner classDefiner;
        if (majorVersion < 15) {
            classDefiner = new Java8ClassDefiner(majorVersion, caller, targetClass);
        } else {
            classDefiner = new Java17ClassDefiner(majorVersion, caller, targetClass);
        }
        return new ClassDefinerAdapter(majorVersion, caller, targetClass, classDefiner);
    }

    @Override
    public Class<?> defineClass(byte[] classBytes) throws Exception {
        return classDefiner.defineClass(classBytes);
    }

    @Override
    public MethodHandle find(Class<?> refc, String name, MethodType type) {
        return classDefiner.find(refc, name, type);
    }
}